#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：back 
@File    ：member_svc.py
@IDE     ：PyCharm 
@Author  ：七分是你
@Date    ：2024/6/29 下午10:55 
@explain : 
"""
import time

from cerberus import Validator
from fastapi import Request

from app import dao
from app import utils
from app.types import appproto


class MemberService:
    """用户中心"""

    @classmethod
    def get_guest_book_list(cls, uid: int, page: int = 1, page_size: int = 10,
                            request: Request = None) -> utils.HttpResponse:
        where = {"uid": uid}
        bookinfo = dao.GuestbookQueryDao.find(**where)

        wheres = {"whereOr": {"parent_id": bookinfo.id, "id": bookinfo.id, "uid": uid}}

        total, result = dao.GuestbookQueryDao.list(page=page, page_size=page_size, **wheres)
        if total == 0:
            return utils.ResponseSuccess(None)
        # 格式化数据
        records_list = []
        for record in result:
            parent_records = {'id': record.id, 'uid': record.uid, 'content': record.content,
                              'suggest': record.suggest, 'parent_id': record.parent_id,
                              'types': record.types, 'entryname': record.entryname,
                              'constructionunitname': record.constructionunitname,
                              'zbdwname': record.zbdwname, 'phonenumber': record.phonenumber,
                              'title': record.title, 'lock': record.lock,
                              'addtime': record.addtime, 'reply_data': []}
            records_list.append(parent_records)
        records_list = cls.build_nested_records(records_list)

        return utils.ResponseSuccess({"total": total, "records": records_list})

    @classmethod
    def add(cls, data: appproto.GuestBookRequestData) -> utils.HttpResponse:
        rules = {
            'content': {
                'type': 'string',
                'required': True
            }
        }
        validator = Validator(rules, allow_unknown=True)
        input_data = data.model_dump()
        print("document===", input_data)
        if not validator.validate(input_data):
            errmsg = ''
            if 'content' in validator.errors:
                errmsg = '内容必填 '
            return utils.ResponseFail(errmsg, -3)
        input_data['addtime'] = int(time.time())
        result = dao.GuestbookOperateDao.save(input_data)
        if result:
            return utils.ResponseSuccess("提交成功")
        else:
            return utils.ResponseFail("提交失败", -3)

    @classmethod
    def get_guestbook_info(cls, uid, request: Request) -> utils.HttpResponse:
        return utils.ResponseSuccess("")

    @classmethod
    def build_nested_records(cls, records):
        # 创建一个字典，用于存储父级记录及其子级列表
        parent_records = {record['id']: record for record in records if record['parent_id'] is None}
        # 遍历所有记录，将子级添加到对应的父级record的reply_data列表中
        for record in records:
            if record['parent_id'] in parent_records:
                parent_records[record['parent_id']]['reply_data'].append(record)
        # 返回处理后的顶级记录列表
        return list(parent_records.values())

    @classmethod
    def add_cmp(cls, data: appproto.ComplaintData) -> utils.HttpResponse:
        rules = {
            'complainttype': {
                'type': 'string',
                'required': True
            }, 'content': {
                'type': 'string',
                'required': True
            }, 'project': {
                'type': 'string',
                'required': True
            }, 'zbdwname': {
                'type': 'string',
                'required': True
            }, 'signcontract': {
                'type': 'integer',
                'required': True
            }, 'contractattachments': {
                'type': 'string',
                'required': True
            }, 'attendance': {
                'type': 'integer',
                'required': True
            }, 'totalattendance': {
                'type': 'integer',
                'required': True
            }, 'workt': {
                'type': 'string',
                'required': True
            }, 'payoff': {
                'type': 'integer',
                'required': True
            }, 'amount': {
                'type': 'integer',
                'required': True
            }, 'arrearsamount': {
                'type': 'integer',
                'required': True
            }, 'unpaidwagest': {
                'type': 'integer',
                'required': True
            }, 'wagearrearspep': {
                'type': 'integer',
                'required': True
            }, 'totalamountwages': {
                'type': 'integer',
                'required': True
            }, 'name': {
                'type': 'string',
                'required': True
            }, 'card': {
                'type': 'string',
                'required': True
            }, 'phone': {
                'type': 'string',
                'required': True
            }, 'nation': {
                'type': 'string',
                'required': True
            }, 'area': {
                'type': 'string',
                'required': True
            }, 'address': {
                'type': 'string',
                'required': True
            }, 'reportfiles': {
                'type': 'string',
                'required': True
            }
        }
        validator = Validator(rules, allow_unknown=True)
        input_data = data.model_dump()
        print("document===", input_data)
        if not validator.validate(input_data):
            print("input_data", validator.errors)
            errmsg = '请填写完每个表单项'
            return utils.ResponseFail(errmsg, -3)
        input_data['addtime'] = int(time.time())
        result = dao.ComplaintOperateDao.save(input_data)
        if result:
            return utils.ResponseSuccess("提交成功")
        else:
            return utils.ResponseFail("提交失败", -3)

    @classmethod
    def get_complaint_list(cls, uid: int, page: int = 1, page_size: int = 10,
                           request: Request = None) -> utils.HttpResponse:
        where = {"uid": uid}
        total, result = dao.ComplaintQueryDao.list(page=page, page_size=page_size, **where)
        if total == 0:
            return utils.ResponseSuccess(None)
        # 格式化数据
        records_list = []

        for record in result:
            parent_records = {'id': record.id, 'complaint': record.complaint, 'uid': record.uid,
                              'complainttype': record.complainttype,
                              'content': record.content, 'project': record.project,
                              'zbdwname': record.zbdwname, 'signcontract': record.signcontract,
                              'contractattachments': record.contractattachments,
                              'attendance': record.attendance, 'totalattendance': record.totalattendance,
                              'workt': record.workt, 'payoff': record.payoff,
                              'amount': record.amount, 'arrearsmonths': record.arrearsmonths,
                              'arrearsamount': record.arrearsamount,
                              'unpaidwagest': record.unpaidwagest, 'wagearrearspep': record.wagearrearspep,
                              'totalamountwages': record.totalamountwages,
                              'name': record.name, 'card': record.card, 'phone': record.phone, 'nation': record.nation,
                              'area': record.area, 'address': record.address, 'reportfiles': record.reportfiles,
                              'addtime': utils.StringUtil.format_timestamp_to_str(record.addtime),
                              'status': record.status, 'reply_content': record.reply_content,
                              'reply_time': utils.StringUtil.format_timestamp_to_str(
                                  record.reply_time) if record.reply_time else '正在受理中',

                              }
            records_list.append(parent_records)

        return utils.ResponseSuccess({"total": total, "records": records_list})
